﻿using System;
using EPiAbstractions.Community;
using EPiServer.Common.Security;
using JoelAbrahamsson.TestUtilities;
using Moq;
using StructureMap.AutoMocking;
using Xunit;

namespace JoelAbrahamsson.MetaWeblog.Tests
{
    public class GetUsersBlogsTests
    {
        [Fact]
        public void GivenUserCredentials_GetUsersBlogs_ThrowsExceptionIfUserAuthenticationFails()
        {
            string username = RandomValues.String;
            string password = RandomValues.String;
            MoqAutoMocker<MetaWeblogHandler> metaWeblogHandlerAutoMocker = new MoqAutoMocker<MetaWeblogHandler>();
            Mock<IDefaultSecurityHandlerFacade> fakeSecurityHandler = Mock.Get(metaWeblogHandlerAutoMocker.Get<IDefaultSecurityHandlerFacade>());
            IUser user = null;
            fakeSecurityHandler.Setup(handler => handler.AuthenticateUser(username, password, out user)).Returns(false);

            Exception thrownException = Record.Exception(() => metaWeblogHandlerAutoMocker.ClassUnderTest.GetUsersBlogs(string.Empty, username, password));

            Assert.NotNull(thrownException);
        }

        [Fact]
        public void GetUsersBlogs_ReturnsBlogInfosFromBlogProvider()
        {
            BlogInfo[] expectedBlogs = new[] { new BlogInfo() };
            MoqAutoMocker<MetaWeblogHandler> metaWeblogHandlerAutoMocker = new MoqAutoMocker<MetaWeblogHandler>();
            Mock<IDefaultSecurityHandlerFacade> fakeSecurityHandler = Mock.Get(metaWeblogHandlerAutoMocker.Get<IDefaultSecurityHandlerFacade>());
            IUser user = null;
            fakeSecurityHandler.Setup(handler => handler.AuthenticateUser(It.IsAny<string>(), It.IsAny<string>(), out user)).Returns(true);
            Mock<IBlogProvider> fakeBlogProvider = Mock.Get(metaWeblogHandlerAutoMocker.Get<IBlogProvider>());
            fakeBlogProvider.Setup(provider => provider.GetUsersBlogs(user)).Returns(expectedBlogs);

            BlogInfo[] returnedBlogs = metaWeblogHandlerAutoMocker.ClassUnderTest.GetUsersBlogs(string.Empty, RandomValues.String, RandomValues.String);

            Assert.Equal<BlogInfo[]>(expectedBlogs, returnedBlogs);
        }
    }
}
